//
//  ChooseVechileViewController.m
//  WHB_logist
//
//  Created by 徐国庆 on 15/12/22.
//  Copyright (c) 2015年 turing. All rights reserved.
//

#import "ChooseVechileViewController.h"
#import "chooseVechileCell.h"
#import "licensePlateList.h"
#import "UtilsHelper.h"
#import "vechileDetailViewController.h"

@interface ChooseVechileViewController ()<UITableViewDataSource,UITableViewDelegate>


@property(nonatomic, strong)UITableView    *tableView;       // 列表
@property(nonatomic, strong)NSMutableArray *sourceArr;       // 数据源
@property(nonatomic, strong)goodsList      *goods;           // 上一页传过来的货品
@property(nonatomic, strong)NSMutableArray *chooseLicenseArr;// 被选中车辆数组

@end

@implementation ChooseVechileViewController

//- (instancetype)initWithGoodsList:(goodsList *)goods{
//    self = [super init];
//    if (self) {
//        _goods = goods;
//        _sourceArr = [NSMutableArray new];
//        _chooseLicenseArr = [NSMutableArray new];
//    }
//    return self;
//}

- (instancetype)initWithGoodsList:(goodsList *)goods tempArr:(NSMutableArray *)tempArr{
    self = [super init];
    if (self) {
        _goods = goods;
        _sourceArr = [NSMutableArray new];
        [_sourceArr addObjectsFromArray:tempArr];
        _chooseLicenseArr = [NSMutableArray new];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navtitle.text = @"选择车辆";
    [self initWithView];
    [self loadData];
}
#pragma mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.sourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    licensePlateList *licensePlate = [self.sourceArr objectAtIndex:indexPath.row];
    static NSString *indentifer = @"chooseVechileCell";
    chooseVechileCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifer];
    if (cell == nil) {
        cell = [[chooseVechileCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifer];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.topLineLabel.backgroundColor = [UIColor HexStrWithColor:@"F0F0F0"];
    cell.topLineLabel.layer.borderColor = [UIColor HexStrWithColor:@"d0d0d0"].CGColor;
    [cell.chooseButton setImage:[UIImage imageNamed:@"dx"] forState:UIControlStateNormal];
    cell.chooseButton.tag = indexPath.row;
    [cell.chooseButton setImage:[UIImage imageNamed:@"dui"] forState:UIControlStateSelected];
    [cell.chooseButton setSelected:NO];
    [cell.chooseButton addTarget:self action:@selector(chooseButtonAction:) forControlEvents:UIControlEventTouchDown];

    cell.vechileImageView.backgroundColor = [UIColor brownColor];
    cell.vechileNumberLabel.text = licensePlate.licensePlate;
    cell.driverLabel.text = licensePlate.driverName;
    [cell.driverLabel sizeToFit];
    cell.weightLabel.text = licensePlate.weight;
    [cell.weightLabel sizeToFit];
    if ([UtilsHelper isEmptyString:licensePlate.startAddressName]) {
        [cell.roadLineView addSubview:[self titleAndContent:nil andContent:@"线路未发布" withToAddress:nil]];
    } else{
        [cell.roadLineView addSubview:[self titleAndContent:@"地址:" andContent:licensePlate.startAddressName withToAddress:licensePlate.endAddressName]];
    }
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld", indexPath.row);
    licensePlateList *licensePlateLi = [self.sourceArr objectAtIndex:indexPath.row];
    NSInteger num = [licensePlateLi.truckId integerValue];
    NSNumber * nums = @(num);
    [DataController getTruckDetail:nums
                            userId:[NSNumber numberWithInt:9]
                      licensePlate:licensePlateLi.licensePlate
                              imei:@"D9B99A6C-1C68-475A-AF48-B0338D8213DD"
                         withBlock:^(NSDictionary *result) {
                            
                             if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                                 
                                 NSDictionary *data = [result objectForKey:@"data"];
                                 
                                 licensePlateList *licensePlate = [MTLJSONAdapter modelOfClass:[licensePlateList class] fromJSONDictionary:data error:nil];
                                 
                                 vechileDetailViewController *vechileDetailVC = [[vechileDetailViewController alloc] initWithLicensePlateList:licensePlate];
                                 [self.navigationController pushViewController:vechileDetailVC animated:YES];
                             }
                             NSLog(@"result == %@", result);
                             
                         }];
    
    
}

#pragma mark 选择按钮事件
- (void)chooseButtonAction:(UIButton *)button{
    licensePlateList *license = [self.sourceArr objectAtIndex:button.tag];
    if (button.selected == NO) {
        [button setSelected:YES];
        [self.chooseLicenseArr addObject:license];
    } else{
        [button setSelected:NO];
        [self.chooseLicenseArr removeObject:license];
    }
}

#pragma mark 导航栏右侧选择完成按钮
- (void)rightButtonAction:(UIButton *)button{
    float weight = 0;
    for (licensePlateList *tempLicense in self.chooseLicenseArr) {
        weight += [tempLicense.weight floatValue];
    }
    if ([_goods.weight floatValue] > weight) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"系统提示" message:@"多选车型载重不够" delegate:nil cancelButtonTitle:@"确 认" otherButtonTitles:nil, nil];
        [alert show];
    } else{
        NSString *truckid = @"";
        for (licensePlateList *tempLicense in self.chooseLicenseArr) {
            if ([truckid isEqualToString:@""]) {
                truckid = [NSString stringWithFormat:@"%@%@", truckid, tempLicense.truckId];
            } else{
                truckid = [NSString stringWithFormat:@"%@,%@", truckid, tempLicense.truckId];
            }
        }
        NSInteger num = [_goods.goodsId integerValue];
        NSNumber *nums = @(num);
        [DataController changeOrderStatus:[NSNumber numberWithInt:5]//nums
                                    orgId:[NSNumber numberWithInt:9]
                                  orderId:[NSNumber numberWithInt:0]
                                   userId:[NSNumber numberWithInt:9]
                                  truckId:@"5"//truckid
                                     type:@"1"
                                     note:@""
                                     imei:@"D9B99A6C-1C68-475A-AF48-B0338D8213DD"
                                withBlock:^(NSDictionary *result) {
                                    if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                                        self.sendProvince(@"");
                                        [self.navigationController popViewControllerAnimated:YES];
                                    }
                                }];
    }
}


/**
 *  初始化视图
 */
- (void)initWithView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, kUIScreenHeight - kNavHeight) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    // 右侧按钮
    [self.rightButton setTitle:@"选择完成" forState:UIControlStateNormal];
    self.rightButton.frame = CGRectMake(0, 0, 60, 30);
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
    self.rightButton.backgroundColor = [UIColor HexStrWithColor:@"FF8040"];
    self.rightButton.layer.masksToBounds = YES;
    self.rightButton.layer.cornerRadius = 4;
    [self.rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchDown];
}

#pragma mark 自定义第一个、第四个cell
- (UIView *)titleAndContent:(NSString *)title andContent:(NSString *)content withToAddress:(NSString *)toAddress{
    UIView *bottomView = [[UIView alloc] init];
    
    // 标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 0, 20)];
    titleLabel.text = @"";
    titleLabel.textAlignment = 2;
    [bottomView addSubview:titleLabel];
    
    // 内容
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleLabel.frame.origin.x + titleLabel.frame.size.width , 10, 150, 20)];
    contentLabel.text = content;
    contentLabel.textAlignment = 0;
    [contentLabel sizeToFit];
    if ([contentLabel.text isEqualToString:@"已确认"] || [contentLabel.text isEqualToString:@"线路未发布"]) {
        contentLabel.textColor = [UIColor HexStrWithColor:@"8CEA00"];
    } else if ([contentLabel.text isEqualToString:@"未确认"]){
        contentLabel.textColor = [UIColor HexStrWithColor:@"FF2D2D"];
    }
    [bottomView addSubview:contentLabel];
    
    if ([title isEqualToString:@"地址:"]) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(contentLabel.frame.origin.x + contentLabel.frame.size.width + 5, contentLabel.frame.origin.y + 5, 18 / 2.0, 21 / 2.0)];
        imageView.image = [UIImage imageNamed:@"jt_xl"];
        [bottomView addSubview:imageView];
        
        UILabel *toAddLabel = [[UILabel alloc] initWithFrame:CGRectMake(imageView.frame.origin.x + imageView.frame.size.width + 5, contentLabel.frame.origin.y, 200, 20)];
        toAddLabel.text = toAddress;
        [bottomView addSubview:toAddLabel];
    }
    
    return bottomView;
}

/**
 *   获取物流商公司所有车牌号信息
 */
- (void)loadData{
    }

- (void)btnDelete:(UIButton *)button{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
